package net.acnull.arpg.rpg.potion;

import com.destroystokyo.paper.ParticleBuilder;
import net.acnull.arpg.Main;
import net.acnull.arpg.particle.RedStoneParticleBuilder;
import net.acnull.arpg.rpg.AbstractRPG;
import net.acnull.arpg.rpg.RPGManager;
import net.acnull.arpg.rpg.skill.Skill;
import net.acnull.arpg.rpg.skill.Skillable;
import net.acnull.arpg.rpg.skill.skills.EffectSkill;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Particle;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.inventory.ItemStack;

public class ExplodingPotion extends Potion{
    static {
        Bukkit.getPluginManager().registerEvents(new ExplodingListener(), Main.getPlugin(Main.class));
    }

    public ExplodingPotion(LivingEntity entity, int time) {
        super(entity, time);
    }

    @Override
    public void next() {
        new RedStoneParticleBuilder().color(Color.RED)
                .location(getEntity().getEyeLocation().add(0,1,0))
                .count(5).spawn();
    }

    @Override
    public void onDie() {
        getEntity().getWorld().createExplosion(getEntity().getLocation(),3,false);
    }

    public static class ExplodingListener implements Listener {
        @EventHandler
        public void onHurt(EntityDamageEvent event){
            if(event.getCause()!= EntityDamageEvent.DamageCause.BLOCK_EXPLOSION){
                return;
            }
            if(!(event.getEntity() instanceof LivingEntity)){
                return;
            }
            ItemStack item=((LivingEntity) event.getEntity()).getEquipment().getItemInMainHand();
            if(item!=null&&item.hasItemMeta()&&item.getItemMeta().hasLore()){
                AbstractRPG rpg= RPGManager.getInstance().getRPGByFirstLore(item.getItemMeta().getLore().get(0));
                if(rpg instanceof Skillable){
                    Skill skill=((Skillable)rpg).getSkill();
                    if(skill instanceof EffectSkill){
                        for(PotionBuilder potion:((EffectSkill) skill).getPotions()){
                            if(potion.getClazz().equals(ExplodingPotion.class)){
                                event.setCancelled(true);
                            }
                        }
                    }
                }
            }
        }
    }
}
